package cc.codeshop.aidlclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import cc.codeshop.aidlserver.ICallback;
import cc.codeshop.aidlserver.ILogicInterface;
import cc.codeshop.aidlserver.Person;

public class MainActivity extends Activity {
	
	private ILogicInterface logicInterface;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	private ServiceConnection connection  = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.d("cc", "onServiceDisconnected");
			logicInterface = null;
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.d("cc", "onServiceConnected");
			logicInterface = ILogicInterface.Stub.asInterface(service);
		}
	};
	
	public void testBind(View view) {
		Intent intent = new Intent("cc.codeshop.aidlserver.ILogicInterface");
		bindService(intent, connection, BIND_AUTO_CREATE);
		//按Home键回到桌面没有解绑ServiceConnection的话会报：Activity cc.codeshop.aidlclient.MainActivity has leaked ServiceConnection cc.codeshop.aidlclient.MainActivity$1@42bf43f8 that was originally bound here
	}
	
	public void testUnbind(View view) {
		unbindService(connection);
	}

	public void testInvokeSimpleParam(View view) {
		try {
			logicInterface.invokeSimpleParam(12, 2.8f, true, "Stan Yung");
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	public void testInvokeObjectParam(View view) {
		try {
			Person inPerson = new Person();
			inPerson.setId(801);
			inPerson.setName("Stan 1");
			Person outPerson = new Person();
			outPerson.setId(802);
			outPerson.setName("Stan 2");
			Person inoutPerson = new Person();
			inoutPerson.setId(803);
			inoutPerson.setName("Stan 3");
			logicInterface.invokeObjectParam(inPerson, outPerson, inoutPerson);
			System.out.println("inPerson = " + inPerson + ", outPerson = " + outPerson + ", inoutPerson = " + inoutPerson);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	public void testInvokeWithCallback(View view) {
		try {
			ICallback callback = new ICallback.Stub() {
				@Override
				public void onInvokeFinished(int result, String message) throws RemoteException {
					System.out.println(String.format("onInvokeFinished : result = %d, message = %s ", result, message )); 
				}
			};
			logicInterface.invokeWithCallback("Hello, Stan!", callback);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	
}
